<template>
  <div class="coach-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>教练管理</span>
        </div>
      </template>
      <div class="content-body">
        <!-- 搜索和筛选区域 -->
        <div class="search-filter">
          <el-input 
            v-model="queryForm.name"
            placeholder="请输入教练姓名搜索"
            style="width: 200px; margin-right: 10px;"
            prefix-icon="Search"
            clearable
          />
          <el-button type="primary" @click="getList">搜索</el-button>
          <el-button type="primary" @click="handleAddCoach">新增教练</el-button>
        </div>
        
        <!-- 教练列表 -->
        <el-table :data="tableData" style="width: 100%; margin-top: 20px;">
          <el-table-column prop="id" label="教练ID" width="80" />
          <el-table-column prop="name" label="教练姓名" width="120" />
          <el-table-column label="教练图片" width="80">
            <template #default="scope">
              <el-image
                v-if="scope.row.avatar"
                :src="scope.row.avatar.startsWith('/api') ? scope.row.avatar : '/api' + scope.row.avatar"
                :preview-src-list="[scope.row.avatar.startsWith('/api') ? scope.row.avatar : '/api' + scope.row.avatar]"
                style="width: 40px; height: 40px; border-radius: 50%;"
              />
              <div v-else class="no-avatar" style="width: 40px; height: 40px; border-radius: 50%; background-color: #e6f4ff; display: flex; align-items: center; justify-content: center;">
                <span style="color: #1890ff;">{{ scope.row.name.charAt(0) }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="qualification" label="教练资质" width="150" />
          <el-table-column prop="experience" label="教学经验" width="100" />
          <el-table-column prop="price" label="价格(元/小时)" width="120" />
          <el-table-column prop="location" label="教学地点" width="150" />
          <el-table-column prop="rating" label="平均评分" width="100" />
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEditCoach(scope.row)">编辑</el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="handleDeleteCoach(scope.row.id)"
                v-if="!isDeleting"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination" style="margin-top: 20px; text-align: right;">
          <el-pagination 
            v-model:current-page="queryForm.pageNum"
            v-model:page-size="queryForm.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 新增/编辑教练弹窗 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="800px"
      @close="resetForm"
    >
      <el-form 
        ref="coachFormRef" 
        :model="coachForm" 
        :rules="formRules" 
        label-width="100px"
      >
        <el-form-item label="教练姓名" prop="name">
          <el-input v-model="coachForm.name" placeholder="请输入教练姓名" />
        </el-form-item>
        <el-form-item label="教练资质" prop="qualification">
          <el-input v-model="coachForm.qualification" placeholder="请输入教练资质" />
        </el-form-item>
        <el-form-item label="教学经验" prop="experience">
          <el-input v-model.number="coachForm.experience" placeholder="请输入教学经验(年)" type="number" />
        </el-form-item>
        <el-form-item label="教学特点" prop="teachingFeatures">
          <el-input v-model="coachForm.teachingFeatures" type="textarea" placeholder="请输入教学特点" :rows="3" />
        </el-form-item>
        <el-form-item label="可预约时间" prop="availableTime">
          <el-input v-model="coachForm.availableTime" type="textarea" placeholder="请输入可预约时间，如：周一至周五 10:00-20:00" :rows="2" />
        </el-form-item>
        <el-form-item label="教学地点" prop="location">
          <el-input v-model="coachForm.location" placeholder="请输入教学地点" />
        </el-form-item>
        <el-form-item label="价格(元/小时)" prop="price">
          <el-input v-model.number="coachForm.price" placeholder="请输入每小时价格" type="number" />
        </el-form-item>
        <el-form-item label="用户评价" prop="comments">
          <el-input v-model="coachForm.comments" type="textarea" placeholder="请输入用户评价" :rows="3" />
        </el-form-item>
        <el-form-item label="评分" prop="rating">
          <el-input v-model.number="coachForm.rating" placeholder="请输入评分(1-5)" type="number" :min="1" :max="5" />
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNo">
          <el-input v-model="coachForm.phoneNo" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="微信号" prop="wechat">
          <el-input v-model="coachForm.wechat" placeholder="请输入微信号" />
        </el-form-item>
        <el-form-item label="教练图片" prop="avatar">
          <el-upload
            class="avatar-upload"
            drag
            :action="uploadUrl"
            :headers="uploadHeaders"
            :on-success="handleImageUploadSuccess"
            :on-error="handleImageUploadError"
            :before-upload="beforeImageUpload"
            :show-file-list="false"
            accept="image/*"
          >
            <div v-if="!coachForm.avatar">
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                拖拽图片到此处或 <em>点击上传</em>
              </div>
            </div>
            <div v-else class="image-preview">
              <img 
                :src="coachForm.avatar.startsWith('/api') ? coachForm.avatar : '/api' + coachForm.avatar"
                alt="教练图片" 
                class="uploaded-image"
              >
              <el-button 
                type="danger" 
                size="small" 
                @click.stop="removeImage"
              >
                删除图片
              </el-button>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, UploadFilled } from '@element-plus/icons-vue'
import { coachList, deleteCoach,addOrUpdateCoach} from '@/request/coach.js'

// 表格数据
const tableData = ref([])
const total = ref(0)
const isDeleting = ref(false)

// 查询表单
const queryForm = ref({
  pageNum: 1,
  pageSize: 10,
  name: '',
  type: ''
})

const getList = ()=>{
  coachList(queryForm.value).then(res=>{
      tableData.value = res.records
      total.value = res.total
      console.log(tableData.value)
  }).catch(err=>{
    ElMessage.error(err.message)
  })
}

getList();

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const editingCoachId = ref(null)
const coachFormRef = ref(null)

// 上传配置
const uploadUrl = '/api/system/file/uploadFile'
const uploadHeaders = {
  Authorization: localStorage.getItem('token') || ''
}

// 教练表单数据
const coachForm = reactive({
  name: '',
  qualification: '',
  experience: 0,
  teachingFeatures: '',
  availableTime: '',
  location: '',
  price: 0,
  comments: '',
  rating: 5,
  avatar: '', // 新增图片字段
  phoneNo: '', // 新增手机号字段
  wechat: '' // 新增微信号字段
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入教练姓名', trigger: 'blur' },
    { min: 2, max: 50, message: '教练姓名长度应在 2 到 50 个字符之间', trigger: 'blur' }
  ],
  qualification: [
    { required: true, message: '请输入教练资质', trigger: 'blur' },
    { min: 2, message: '教练资质不能少于 2 个字符', trigger: 'blur' }
  ],
  experience: [
    { required: true, message: '请输入教学经验', trigger: 'blur' },
    { type: 'number', min: 0, message: '教学经验不能为负数', trigger: 'blur' }
  ],
  teachingFeatures: [
    { required: true, message: '请输入教学特点', trigger: 'blur' },
    { min: 5, message: '教学特点不能少于 5 个字符', trigger: 'blur' }
  ],
  availableTime: [
    { required: true, message: '请输入可预约时间', trigger: 'blur' },
    { min: 5, message: '可预约时间不能少于 5 个字符', trigger: 'blur' }
  ],
  location: [
    { required: true, message: '请输入教学地点', trigger: 'blur' },
    { min: 2, message: '教学地点不能少于 2 个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格不能为负数', trigger: 'blur' }
  ],
  rating: [
    { required: true, message: '请输入评分', trigger: 'blur' },
    { type: 'number', min: 1, max: 5, message: '评分应在 1 到 5 之间', trigger: 'blur' }
  ],
  phoneNo: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码格式', trigger: 'blur' }
  ],
  wechat: [
    { required: true, message: '请输入微信号', trigger: 'blur' },
    { min: 2, max: 20, message: '微信号长度应在 2 到 20 个字符之间', trigger: 'blur' }
  ]
}


// 分页处理
const handleSizeChange = (size) => {
  queryForm.value.pageSize = size
  getList()
}

const handleCurrentChange = (current) => {
  queryForm.value.pageNum = current
  getList()
}

// 图片上传前检查
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2
  
  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB！')
    return false
  }
  return true
}

// 图片上传成功
const handleImageUploadSuccess = (response, file) => {
  console.log('图片上传响应:', response)
  if (response && response.data) {
    // 存储原始路径用于提交，不添加/api前缀
    coachForm.avatar = response.data
  } else {
    // 创建本地URL用于预览，但实际提交时可能需要调整
    coachForm.avatar = URL.createObjectURL(file.raw)
  }
  console.log('当前coachForm:', coachForm)
  ElMessage.success('图片上传成功')
}

// 图片上传失败
const handleImageUploadError = (error) => {
  ElMessage.error('图片上传失败')
}

// 删除图片
const removeImage = () => {
  coachForm.avatar = ''
}

// 重置表单
const resetForm = () => {
  if (coachFormRef.value) {
    coachFormRef.value.resetFields()
  }
  editingCoachId.value = null
  Object.keys(coachForm).forEach(key => {
    if (key === 'experience' || key === 'price' || key === 'rating') {
      coachForm[key] = key === 'rating' ? 5 : 0
    } else {
      coachForm[key] = ''
    }
  })
}

// 新增教练
const handleAddCoach = () => {
  resetForm()
  dialogTitle.value = '新增教练'
  dialogVisible.value = true
}

// 编辑教练
const handleEditCoach = (coach) => {
  resetForm()
  dialogTitle.value = '编辑教练'
  editingCoachId.value = coach.id
  
  // 复制教练数据到表单
    setTimeout(() => {
      nextTick(() => {
        Object.keys(coachForm).forEach(key => {
          if (coach.hasOwnProperty(key)) {
            coachForm[key] = coach[key]
          }
        })
        
        // 编辑模式下，存储原始路径用于提交，不添加/api前缀
        coachForm.avatar = coach.avatar
      })
    }, 100)
  
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = () => {
  coachFormRef.value.validate((valid) => {
    if (valid) {
      // 创建提交表单数据的副本
      const submitData = { ...coachForm }
      
      // 提交时移除/api前缀（如果存在）
      if (submitData.avatar && submitData.avatar.startsWith('/api')) {
        submitData.avatar = submitData.avatar.substring(4)
      }
      
      if (editingCoachId.value) {
        // 编辑模式
        submitData.id = editingCoachId.value
        addOrUpdateCoach(submitData).then(res => {
          ElMessage.success('教练信息更新成功')
          dialogVisible.value = false
          resetForm()
          getList()
        }).catch(() => {
          ElMessage.error('教练信息更新失败')
        })
      } else {
        // 新增模式
        addOrUpdateCoach(submitData).then(res => {
          ElMessage.success('教练信息添加成功')
          dialogVisible.value = false
          resetForm()
          getList()
        }).catch(() => {
          ElMessage.error('教练信息添加失败')
        })
      }
    }
  })
}

// 删除教练
const handleDeleteCoach = (id) => {
  ElMessageBox.confirm('确定要删除该教练信息吗？', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    isDeleting.value = true
    deleteCoach(id).then(res => {
      ElMessage.success('教练信息删除成功')
      getList()
    }).catch(() => {
      ElMessage.error('教练信息删除失败')
    }).finally(() => {
      isDeleting.value = false
    })
  }).catch(() => {
    // 用户取消删除
  })
}

// 初始加载数据
getList()
</script>

<style scoped>
.coach-management {
  padding: 20px;
}

.search-filter {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.avatar-upload {
  margin-top: 10px;
}

.image-preview {
  margin-top: 10px;
}

.image-preview img {
  max-width: 200px;
  max-height: 200px;
  border: 1px solid #ddd;
  padding: 5px;
  border-radius: 4px;
}

.no-avatar {
  background-color: #f0f0f0;
  border: 1px dashed #d9d9d9;
}
</style>